package com.sgb.kjwl.view.ui.fragment.transport;

import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AppFragSelfCarManagerBinding;
import com.sgb.kjwl.model.entity.MyCarInfoEntity;
import com.sgb.kjwl.model.response.ListResponseV1;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.ui.activity.transport.DriverBindActivity;
import com.sgb.kjwl.view.ui.activity.transport.SelfCarDetailActivity;
import com.sgb.kjwl.view.ui.adapter.transport.SelfCarManagerAdapter;
import com.sgb.kjwl.viewmodel.transport.SelfCarManagerViewModel;
import com.swgk.core.common.base.BaseFragment;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.ArrayUtil;
import com.swgk.core.util.NumberUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 杨畔
 * @date: 2021/10/9 10:59
 * @Description: 自营车辆管理内容页
 */
public class SelfCarManagerFragment extends BaseFragment<SelfCarManagerViewModel, AppFragSelfCarManagerBinding> {

    private List<MyCarInfoEntity> mList;
    private SelfCarManagerAdapter mAdapter;
    //点击下标
    private int mClickIndex = -1;
    //回到页面时是否需要刷新数据(绑定/解绑操作触发)
    private boolean mIsNeedRefresh;

    public static SelfCarManagerFragment newInstance(int type) {
        Bundle args = new Bundle();
        args.putInt(RouterKey.TYPE, type);
        SelfCarManagerFragment fragment = new SelfCarManagerFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int layoutId() {
        return R.layout.app_frag_self_car_manager;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(SelfCarManagerViewModel.class);
    }

    @Override
    protected void init() {
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        initRecycler();
        initEvent();
        initData();
    }

    private void initRecycler() {
        mList = new ArrayList<>();
        mAdapter = new SelfCarManagerAdapter(mList);
        mBinding.rvSelfCarManager.setLayoutManager(new LinearLayoutManager(_mActivity));
        DividerDecoration.builder(_mActivity)
                .color(Color.TRANSPARENT)
                .size(10, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(mBinding.rvSelfCarManager);
        mAdapter.bindToRecyclerView(mBinding.rvSelfCarManager);
    }

    private void initEvent() {
        mBinding.srlSelfCarManager.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                mViewModel.getCarList(_mActivity, false);
            }

            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                mViewModel.getCarList(_mActivity, true);
            }
        });
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            mClickIndex = position;
            MyCarInfoEntity entity = mList.get(position);
            if (view.getId() == R.id.cl_item) {
                SelfCarDetailActivity.start(_mActivity, NumberUtil.convertToLong(entity.getCarNo()));
            } else if (view.getId() == R.id.tv_bind) {
                DriverBindActivity.start(_mActivity, NumberUtil.convertToLong(entity.getNo()));
            } else if (view.getId() == R.id.tv_unbind) {
                //检查是否有订单
                mViewModel.checkOrder(_mActivity, entity.getDriverNo(), entity.getCarNo());
            }
        });
        //接口回调
        mViewModel.ldList.observe(this, this::syncList);
        mViewModel.ldCheckOrder.observe(this, haveOrder -> {
            if (haveOrder) {
                showUnbindErrorDialog();
                return;
            }
            if (mClickIndex != -1 && mClickIndex < mList.size()) {
                showUnbindDialog(mList.get(mClickIndex));
            }
        });
    }

    private void initData() {
        if (getArguments() != null) {
            mViewModel.mState = getArguments().getInt(RouterKey.TYPE, -1);
        }
        //获取数据
        mViewModel.getCarList(_mActivity, true);
    }

    private void showUnbindErrorDialog() {
        new RoundDialog.Builder(_mActivity)
                .title("提示")
                .content("当前车辆还有进行中的订单，不可解绑")
                .contentGravity(Gravity.CENTER)
                .show();
    }

    private void showUnbindDialog(MyCarInfoEntity entity) {
        new RoundDialog.Builder(_mActivity)
                .title("解绑司机")
                .content(String.format("确定要解除车辆（%s）与司机（%s）的绑定关系吗？"
                        , entity.getCarNumber()
                        , entity.getDriverName()))
                .contentGravity(Gravity.CENTER)
                .confirmCallback(v -> {
                    //调用解绑接口
                    mViewModel.unbindDriver(_mActivity, entity.getNo());
                })
                .show();
    }

    private void syncList(ListResponseV1<List<MyCarInfoEntity>> listResponse) {
        mBinding.srlSelfCarManager.finishRefresh();
        mBinding.srlSelfCarManager.finishLoadMore();
        if (!listResponse.loadSuccess()) {
            if (listResponse.getPageNumber() == 1) {
                mAdapter.setEmptyView(R.layout.layout_null_list_logistics);
            }
        }
        if (listResponse.getPageNumber() == 1) {
            mList.clear();
        }
        if (listResponse.getList() != null) {
            mList.addAll(listResponse.getList());
        }
        mAdapter.notifyDataSetChanged();
        //
        mBinding.srlSelfCarManager.setNoMoreData(!listResponse.haveMoreData());
        //设置空布局
        if (ArrayUtil.isNullOrEmpty(mList)) {
            mAdapter.setEmptyView(R.layout.layout_null_list_logistics);
        }
    }

    @Override
    protected boolean isUseEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(LogisticsEvent event) {
        //解绑/绑定司机，添加/修改车辆信息刷新列表
        if (event.getMessageTag() == EventConstant.EVENT_BIND_DRIVER
                || event.getMessageTag() == EventConstant.EVENT_UNBIND_DRIVER
                || event.getMessageTag() == EventConstant.EVENT_CARINFO_COMMIT) {
            if (isSupportVisible()) {
                mViewModel.getCarList(_mActivity, true);
            } else {
                mIsNeedRefresh = true;
            }
        }
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (mIsNeedRefresh) {
            mIsNeedRefresh = false;
            mViewModel.getCarList(_mActivity, true);
        }
    }

}
